<template>
  <div class="monitor-dashboard" :key="$route.fullPath">
    <!-- 顶部标题 -->
    <header class="dashboard-header">
      <h1>环境监测仪表盘</h1>
      <div class="current-time">{{ currentTime }}</div>
    </header>

    <div class="dashboard-content">
      <!-- 左侧面板 -->
      <section class="left-panel">
        <div class="panel-item aqi-info">
          <h3>实时监测数据</h3>
          <div class="aqi-value">{{ monitorData.aqi }}</div>
          <div class="aqi-details">
            <div class="detail-item" v-for="item in monitorData.details" :key="item.name">
              <span>{{ item.name }}</span>
              <span>{{ item.value }}</span>
            </div>
          </div>
        </div>
        
        <div class="panel-item park-summary">
          <h3>园区环保综合情况</h3>
          <div class="summary-content">
            <div class="summary-item">
              <div class="summary-icon good"></div>
              <div class="summary-info">
                <div class="summary-title">环保设备运行</div>
                <div class="summary-value">正常</div>
              </div>
            </div>
            <div class="summary-item">
              <div class="summary-icon warning"></div>
              <div class="summary-info">
                <div class="summary-title">污染预警</div>
                <div class="summary-value">1起</div>
              </div>
            </div>
            <div class="summary-item">
              <div class="summary-icon good"></div>
              <div class="summary-info">
                <div class="summary-title">处理达标率</div>
                <div class="summary-value">98.5%</div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="panel-item pollution-chart">
          <h3>每日大气污染指数</h3>
          <div ref="pollutionChartRef" class="chart-container"></div>
        </div>
      </section>

      <!-- 中间地图区域 -->
      <section class="map-container">
        <div ref="mapContainer" class="map"></div>
        <div class="map-info-overlay">
          <div class="info-card">
            <h4>园区污染因子信息</h4>
            <div class="factor-list">
              <div class="factor-item" v-for="(factor, index) in pollutionFactors" :key="index">
                <span class="factor-name">{{ factor.name }}</span>
                <div class="factor-bar-container">
                  <div class="factor-bar" :style="{ width: factor.percentage + '%', backgroundColor: factor.color }"></div>
                </div>
                <span class="factor-value">{{ factor.value }}</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- 右侧面板 -->
      <section class="right-panel">
        <div class="panel-item camera-views">
          <h3>天气信息</h3>
          <div class="weather-info">
            <div class="current-weather">
              <div class="weather-icon">
                <i class="weather-sunny"></i>
              </div>
              <div class="weather-details">
                <div class="temperature">23°C</div>
                <div class="weather-desc">晴朗</div>
                <div class="other-info">湿度: 45% | 风力: 3级</div>
              </div>
            </div>
            <div class="weather-forecast">
              <div class="forecast-item" v-for="(item, index) in weatherForecast" :key="index">
                <div class="time">{{ item.time }}</div>
                <div class="icon" :class="item.icon"></div>
                <div class="temp">{{ item.temp }}°</div>
              </div>
            </div>
          </div>
        </div>

        <div class="panel-item trend-chart">
          <h3>监测趋势</h3>
          <div ref="trendChartRef" class="chart-container"></div>
        </div>

        <div class="panel-item composition-chart">
          <h3>资料构成分析</h3>
          <div ref="compositionChartRef" class="chart-container"></div>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useMonitorStore } from '@/stores/monitor'
import { initMap } from '@/utils/map'
import { initCharts } from '@/utils/charts'
import { AMAP_CONFIG, MAP_CONFIG } from '@/config/map'
import dayjs from 'dayjs'

// 状态初始化
const currentTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const monitorStore = useMonitorStore()
const mapContainer = ref<HTMLElement | null>(null)
const pollutionChartRef = ref<HTMLElement | null>(null)
const trendChartRef = ref<HTMLElement | null>(null)
const compositionChartRef = ref<HTMLElement | null>(null)
const map = ref<any>(null)
const currentMapMode = ref('3d')

// 数据初始化
const monitorData = ref({
  aqi: 135,
  details: [
    { name: 'PM2.5', value: 3.5 },
    { name: 'PM10', value: 2.6 },
    { name: 'SO2', value: 3.0 },
    { name: 'NO2', value: 2.0 }
  ]
})

// 模拟天气数据
const weatherForecast = ref([
  { time: '上午', icon: 'weather-sunny', temp: 21 },
  { time: '下午', icon: 'weather-cloudy', temp: 24 },
  { time: '傍晚', icon: 'weather-cloudy', temp: 22 },
  { time: '夜间', icon: 'weather-clear', temp: 19 }
])

// 添加污染因子数据
const pollutionFactors = ref([
  { name: 'VOCs', value: '0.12mg/m³', percentage: 60, color: '#4CAF50' },
  { name: '氮氧化物', value: '0.032mg/m³', percentage: 32, color: '#4CAF50' },
  { name: '二氧化硫', value: '0.018mg/m³', percentage: 18, color: '#4CAF50' },
  { name: '颗粒物', value: '0.045mg/m³', percentage: 45, color: '#FFC107' }
])

// 定时器
let timer: number

onMounted(async () => {
  console.log('初始化地图...')
  if (mapContainer.value) {
    try {
      map.value = await initMap(mapContainer.value, {
        ...MAP_CONFIG,
        ...AMAP_CONFIG
      })
      console.log('地图初始化成功')
      
      // 初始化完成后设置默认模式
      map.value.mapControl.to3D()
    } catch (error) {
      console.error('地图初始化失败:', error)
    }
  }

  // 延迟初始化图表，确保DOM已完全渲染
  setTimeout(() => {
    initCharts({
      pollutionChart: pollutionChartRef.value,
      trendChart: trendChartRef.value,
      compositionChart: compositionChartRef.value
    })
  }, 300)

  // 确保图表在窗口调整大小时重新渲染
  const handleResize = () => {
    clearTimeout(window.resizeTimer)
    window.resizeTimer = setTimeout(() => {
      initCharts({
        pollutionChart: pollutionChartRef.value,
        trendChart: trendChartRef.value,
        compositionChart: compositionChartRef.value
      })
    }, 300)
  }
  
  window.addEventListener('resize', handleResize)

  // 启动定时器
  timer = setInterval(() => {
    currentTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
    monitorStore.fetchData()
  }, 5 * 60 * 1000)
})

onUnmounted(() => {
  clearInterval(timer)
  window.removeEventListener('resize', handleResize)
})

// 地图控制处理
const handleMapControl = (type: string) => {
  if (!map.value || !map.value.mapControl) {
    console.error('地图实例或控制方法未初始化')
    return
  }
  
  try {
    currentMapMode.value = type
    
    switch (type) {
      case '2d':
        map.value.mapControl.to2D()
        break
      case '3d':
        map.value.mapControl.to3D()
        break
      case 'satellite':
        map.value.mapControl.toSatellite()
        break
      case 'road':
        map.value.mapControl.toRoad()
        break
      default:
        console.warn('未知的地图控制类型:', type)
    }
  } catch (error) {
    console.error('地图控制失败:', error)
  }
}

// 添加地图实例监听
watch(() => map.value, (newMap) => {
  console.log('地图实例更新:', newMap ? '已加载' : '未加载')
}, { immediate: true })
</script>

<style lang="scss" scoped>
.monitor-dashboard {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #0a2744 0%, #001529 100%);
  color: #fff;
  padding: 5px;
  box-sizing: border-box;
  overflow: auto;
  display: flex;
  flex-direction: column;

  .dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    height: 28px;

    h1 {
      font-size: 16px;
      margin: 0;
    }
  }

  .dashboard-content {
    display: grid;
    grid-template-columns: 25% 50% 25%;
    gap: 10px;
    flex: 1;
    min-height: 0;
  }

  .left-panel, .right-panel {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .panel-item {
    background: rgba(255,255,255,0.05);
    border: 1px solid rgba(255,255,255,0.1);
    border-radius: 4px;
    padding: 8px;
    margin-bottom: 5px;
    display: flex;
    flex-direction: column;
    
    &:last-child {
      margin-bottom: 0;
      flex: 1;
    }

    h3 {
      margin: 0 0 8px 0;
      font-size: 14px;
      color: #0ff;
    }
  }

  .aqi-value {
    font-size: 32px;
    color: #f00;
    text-align: center;
    margin: 5px 0;
  }

  .aqi-details {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 5px;

    .detail-item {
      display: flex;
      justify-content: space-between;
      padding: 5px;
      background: rgba(255,255,255,0.1);
      border-radius: 4px;
      font-size: 12px;
    }
  }

  .map-container {
    position: relative;
    height: 100%;
    overflow: hidden;
    
    .map {
      width: 100%;
      height: 100%;
      border-radius: 4px;
    }
  }

  .weather-info {
    display: flex;
    flex-direction: column;
    height: auto;
    
    .current-weather {
      display: flex;
      align-items: center;
      padding: 10px;
      background: rgba(0,255,255,0.05);
      border-radius: 4px;
      margin-bottom: 5px;
      
      .weather-icon {
        width: 40px;
        height: 40px;
        margin-right: 15px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .weather-sunny {
          width: 30px;
          height: 30px;
          border-radius: 50%;
          background: #ffcc00;
          box-shadow: 0 0 20px rgba(255, 204, 0, 0.6);
          position: relative;
          
          &:before {
            content: '';
            position: absolute;
            top: -15px;
            left: -15px;
            right: -15px;
            bottom: -15px;
            background: radial-gradient(rgba(255, 204, 0, 0.3), transparent 70%);
          }
        }
      }
      
      .weather-details {
        flex: 1;
        
        .temperature {
          font-size: 24px;
          font-weight: bold;
          color: #fff;
        }
        
        .weather-desc {
          font-size: 14px;
          color: #0ff;
          margin: 2px 0;
        }
        
        .other-info {
          font-size: 12px;
          color: rgba(255,255,255,0.7);
        }
      }
    }
    
    .weather-forecast {
      display: flex;
      justify-content: space-between;
      flex: 1;
      
      .forecast-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 5px;
        background: rgba(255,255,255,0.05);
        border-radius: 4px;
        margin: 0 2px;
        
        &:first-child {
          margin-left: 0;
        }
        
        &:last-child {
          margin-right: 0;
        }
        
        .time {
          font-size: 12px;
          color: #0ff;
          margin-bottom: 5px;
        }
        
        .icon {
          width: 25px;
          height: 25px;
          margin: 5px 0;
          
          &.weather-sunny {
            background: #ffcc00;
            border-radius: 50%;
            box-shadow: 0 0 10px rgba(255, 204, 0, 0.4);
          }
          
          &.weather-cloudy {
            background: linear-gradient(to bottom, #f0f0f0 50%, #aaaaaa 100%);
            border-radius: 12px;
          }
          
          &.weather-clear {
            background: #444;
            border-radius: 50%;
            box-shadow: 0 0 5px rgba(255, 255, 255, 0.2);
            position: relative;
            
            &:after {
              content: '';
              position: absolute;
              top: 5px;
              left: 5px;
              width: 5px;
              height: 5px;
              background: #fff;
              border-radius: 50%;
              opacity: 0.8;
            }
          }
        }
        
        .temp {
          font-size: 14px;
          font-weight: bold;
          color: #fff;
        }
      }
    }
  }

  .chart-container {
    height: 140px;
    background: rgba(255,255,255,0.02);
    border-radius: 4px;
    margin-top: 5px;
  }
  
  .composition-chart .chart-container {
    height: 160px;
  }
}

// 添加园区环保综合情况样式
.park-summary {
  .summary-content {
    display: flex;
    justify-content: space-between;
    
    .summary-item {
      display: flex;
      align-items: center;
      background: rgba(255,255,255,0.05);
      border-radius: 4px;
      padding: 5px;
      width: 30%;
      
      .summary-icon {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        margin-right: 8px;
        
        &.good {
          background: #4CAF50;
          box-shadow: 0 0 5px rgba(76, 175, 80, 0.5);
        }
        
        &.warning {
          background: #FFC107;
          box-shadow: 0 0 5px rgba(255, 193, 7, 0.5);
        }
        
        &.danger {
          background: #F44336;
          box-shadow: 0 0 5px rgba(244, 67, 54, 0.5);
        }
      }
      
      .summary-info {
        flex: 1;
        
        .summary-title {
          font-size: 10px;
          color: rgba(255,255,255,0.7);
        }
        
        .summary-value {
          font-size: 12px;
          font-weight: bold;
          color: #fff;
        }
      }
    }
  }
}

// 添加地图信息覆盖层样式
.map-info-overlay {
  position: absolute;
  bottom: 40px;
  left: 10px;
  z-index: 100;
  
  .info-card {
    background: rgba(0,0,0,0.7);
    border: 1px solid rgba(0,255,255,0.3);
    border-radius: 4px;
    padding: 8px;
    width: 220px;
    max-height: 120px;
    overflow: auto;
    
    h4 {
      margin: 0 0 8px 0;
      font-size: 12px;
      color: #0ff;
    }
    
    .factor-list {
      .factor-item {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        font-size: 11px;
        
        .factor-name {
          width: 60px;
          color: #fff;
        }
        
        .factor-bar-container {
          flex: 1;
          height: 4px;
          background: rgba(255,255,255,0.1);
          margin: 0 5px;
          border-radius: 2px;
          overflow: hidden;
          
          .factor-bar {
            height: 100%;
            border-radius: 2px;
          }
        }
        
        .factor-value {
          width: 60px;
          text-align: right;
          color: rgba(255,255,255,0.8);
        }
      }
    }
  }
}

// 确保图表面板有足够空间
.panel-item.pollution-chart,
.panel-item.trend-chart,
.panel-item.composition-chart {
  min-height: 180px;
}
</style> 